// 安全获取ElMessage
let ElMessage;

// 创建自定义消息提示函数
function createCustomMessage() {
    return {
        success: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.log('Success:', message);
            showCustomMessage(message, 'success');
        },
        error: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.error('Error:', message);
            showCustomMessage(message, 'error');
        },
        warning: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.warn('Warning:', message);
            showCustomMessage(message, 'warning');
        },
        info: function(options) {
            const message = typeof options === 'string' ? options : options.message;
            console.info('Info:', message);
            const msgObj = showCustomMessage(message, 'info');
            return {
                close: function() {
                    if (msgObj && msgObj.element) {
                        document.body.removeChild(msgObj.element);
                    }
                }
            };
        }
    };
}

// 显示自定义消息提示
function showCustomMessage(message, type) {
    // 创建消息元素
    const messageElement = document.createElement('div');
    messageElement.style.position = 'fixed';
    messageElement.style.top = '20px';
    messageElement.style.left = '50%';
    messageElement.style.transform = 'translateX(-50%)';
    messageElement.style.padding = '10px 20px';
    messageElement.style.borderRadius = '4px';
    messageElement.style.zIndex = '9999';
    messageElement.style.boxShadow = '0 4px 12px rgba(0, 0, 0, 0.15)';
    messageElement.style.transition = 'opacity 0.3s, transform 0.3s';
    messageElement.style.opacity = '0';
    messageElement.style.transform = 'translateX(-50%) translateY(-20px)';
    messageElement.textContent = message;
    
    // 根据类型设置样式
    switch (type) {
        case 'success':
            messageElement.style.backgroundColor = '#f0f9eb';
            messageElement.style.color = '#67c23a';
            messageElement.style.border = '1px solid #e1f3d8';
            break;
        case 'error':
            messageElement.style.backgroundColor = '#fef0f0';
            messageElement.style.color = '#f56c6c';
            messageElement.style.border = '1px solid #fde2e2';
            break;
        case 'warning':
            messageElement.style.backgroundColor = '#fdf6ec';
            messageElement.style.color = '#e6a23c';
            messageElement.style.border = '1px solid #faecd8';
            break;
        case 'info':
        default:
            messageElement.style.backgroundColor = '#edf2fc';
            messageElement.style.color = '#909399';
            messageElement.style.border = '1px solid #ebeef5';
            break;
    }
    
    // 添加到页面
    document.body.appendChild(messageElement);
    
    // 触发重绘以应用过渡效果
    setTimeout(() => {
        messageElement.style.opacity = '1';
        messageElement.style.transform = 'translateX(-50%) translateY(0)';
    }, 10);
    
    // 自动关闭（除非是info类型且duration为0）
    const duration = type === 'info' ? 0 : 3000;
    if (duration > 0) {
        setTimeout(() => {
            messageElement.style.opacity = '0';
            messageElement.style.transform = 'translateX(-50%) translateY(-20px)';
            
            setTimeout(() => {
                if (document.body.contains(messageElement)) {
                    document.body.removeChild(messageElement);
                }
            }, 300);
        }, duration);
    }
    
    return { element: messageElement };
}

// 尝试获取ElementPlus，如果不可用则使用自定义消息提示
try {
    if (window.ElementPlus && window.ElementPlus.ElMessage) {
        console.log('成功加载ElementPlus.ElMessage');
        ElMessage = window.ElementPlus.ElMessage;
    } else {
        console.warn('ElementPlus或ElMessage未找到，将使用自定义消息提示');
        ElMessage = createCustomMessage();
    }
} catch (error) {
    console.error('加载ElementPlus时出错:', error);
    ElMessage = createCustomMessage();
}

// 全局变量
let isPRD = true;
let isHeadless = false;
let processingMessage = null;

// DOM元素
let progressContainer;
let progressBar;
let switchElement;
let headlessSwitchElement;
let orderNumbersTextarea;
let startButton;
let resultContainer;
let logContainer;

// 初始化函数
function init() {
    // 获取DOM元素
    progressContainer = document.getElementById('progress-container');
    progressBar = document.getElementById('progress-bar');
    switchElement = document.getElementById('switch');
    headlessSwitchElement = document.getElementById('headless-switch');
    orderNumbersTextarea = document.getElementById('orderNumbers');
    startButton = document.getElementById('startButton');
    resultContainer = document.getElementById('result-container');
    logContainer = document.getElementById('log-container');

    // 绑定事件
    switchElement.addEventListener('change', handleAddressSwitch);
    headlessSwitchElement.addEventListener('change', handleStepsSwitch);
    startButton.addEventListener('click', handleStartClick);
}

// 更新进度条函数
function updateProgress(percent, show = true) {
    if (!progressContainer || !progressBar) return;
    
    if (show) {
        progressContainer.style.display = 'block';
    } else {
        progressContainer.style.display = 'none';
        return;
    }
    
    progressBar.style.width = `${percent}%`;
}

// 环境切换处理函数
function handleAddressSwitch() {
    isPRD = switchElement.checked;
    const environment = isPRD ? 'PRD' : 'UAT';
    
    // 使用ElMessage向用户提示环境切换状态
    ElMessage.info(`环境已切换至${environment}`);
}

// 无头模式切换处理函数
function handleStepsSwitch() {
    isHeadless = headlessSwitchElement.checked;
    
    // 使用ElMessage向用户提示操作步骤切换状态
    ElMessage.info(`操作步骤已${isHeadless ? '显示' : '隐藏'}，${isHeadless ? '将展示自动化操作过程' : '将隐藏自动化操作过程'}`);
}

// 添加日志到页面
function addLog(message, isError = false) {
    if (!logContainer) return;
    
    const logItem = document.createElement('div');
    logItem.className = isError ? 'error-log' : 'info-log';
    logItem.style.color = isError ? '#ff4d4f' : '#52c41a';
    logItem.style.marginBottom = '5px';
    
    const timestamp = new Date().toLocaleTimeString();
    logItem.textContent = `[${timestamp}] ${message}`;
    
    logContainer.appendChild(logItem);
}

// 开始按钮点击处理函数
async function handleStartClick() {
    const orderNumbersText = orderNumbersTextarea.value;
    if (orderNumbersText.trim() === '') {
        ElMessage.warning('请输入订单号');
        return;
    }

    // 禁用按钮，显示进度条
    startButton.disabled = true;
    updateProgress(10);

    // 清空日志和结果容器
    if (logContainer) logContainer.innerHTML = '';
    if (resultContainer) resultContainer.innerHTML = '';

    // 解析订单号
    const orderNumbersArray = orderNumbersText.split('\n')
        .map(num => num.trim())
        .filter(num => num);

    // 检查订单号数量
    if (orderNumbersArray.length > 100) {
        ElMessage.warning('订单号数量超过100个，请减少数量后重试');
        startButton.disabled = false;
        updateProgress(0, false);
        return;
    }

    try {
        // 更新进度条
        updateProgress(20);
        
        // 获取用户设置
        const userSettings = await electronAPI.getUserSettings();
        console.log('获取到的用户设置:', userSettings);
        
        // 显示处理中提示
        processingMessage = ElMessage.info({
            message: 'Processing，please wait...',
            duration: 0,
            showClose: true
        });
        
        // 更新进度条
        updateProgress(30);
        
        // 确定环境地址
        const environment = isPRD ? 'PRD' : 'UAT';
        const address = environment === 'PRD' ? 'http://cnapp.sgs.net/gpo-web/#/' : 'http://cnapp-uat.sgs.net/sgsLogin/';
        
        addLog(`开始处理 ${orderNumbersArray.length} 个订单号，环境: ${environment}`);
        
        // 调用核心脚本
        const { success, data, error } = await pluginAPI.runPluginScript({
            pluginName: 'batch-combine3',
            script: './core.js',
            args: [address, isHeadless, orderNumbersArray, userSettings]
        });
        
        // 脚本执行完成后更新进度
        updateProgress(90);
        
        if (success) {
            // 完成进度条
            updateProgress(100);
            
            // 关闭Processing提示
            if (processingMessage) {
                processingMessage.close();
                processingMessage = null;
            }
            
            ElMessage.success({
                message: 'Finished!',
                duration: 3000
            });
            
            // 显示处理结果
            if (data && Array.isArray(data)) {
                displayResults(data);
                const successCount = data.filter(item => item.success).length;
                const failCount = data.filter(item => !item.success).length;
                const monitoringSuccessCount = data.filter(item => item.success && item.monitoringStatus === true).length;
                const monitoringFailCount = data.filter(item => item.success && item.monitoringStatus === false).length;
                
                addLog(`处理完成，成功: ${successCount}，失败: ${failCount}`);
                // if (successCount > 0) {
                //     addLog(`监控数据发送情况：成功: ${monitoringSuccessCount}，失败: ${monitoringFailCount}，未记录: ${successCount - monitoringSuccessCount - monitoringFailCount}`);
                // }
            } else if (data && data.details && Array.isArray(data.details)) {
                displayResults(data.details);
                const successCount = data.details.filter(item => item.success).length;
                const failCount = data.details.filter(item => !item.success).length;
                const monitoringSuccessCount = data.details.filter(item => item.success && item.monitoringStatus === true).length;
                const monitoringFailCount = data.details.filter(item => item.success && item.monitoringStatus === false).length;
                
                addLog(`处理完成，成功: ${successCount}，失败: ${failCount}`);
                // if (successCount > 0) {
                //     addLog(`监控数据发送情况：成功: ${monitoringSuccessCount}，失败: ${monitoringFailCount}，未记录: ${successCount - monitoringSuccessCount - monitoringFailCount}`);
                // }
            }
            
            // 延迟后隐藏进度条
            setTimeout(() => updateProgress(0, false), 1000);
        } else {
            throw new Error(error || '处理失败');
        }
    } catch (error) {
        // 出错时隐藏进度条
        updateProgress(0, false);
        
        // 关闭Processing提示
        if (processingMessage) {
            processingMessage.close();
            processingMessage = null;
        }
        
        // 添加错误日志
        addLog(error.message || '处理失败', true);
        
        ElMessage.error({
            message: 'Failed, Please check.',
            duration: 5000,
            showClose: true
        });
    } finally {
        // 重新启用按钮
        startButton.disabled = false;
    }
}

// 显示处理结果的函数
function displayResults(results) {
    if (!resultContainer) return;
    
    // 清空容器
    resultContainer.innerHTML = '';
    
    // 创建结果标题
    const resultTitle = document.createElement('h3');
    resultTitle.textContent = 'Combine 操作结果';
    resultTitle.style.marginTop = '20px';
    resultContainer.appendChild(resultTitle);
    
    // 显示处理统计信息
    const statsDiv = document.createElement('div');
    statsDiv.style.marginBottom = '15px';
    statsDiv.style.fontSize = '14px';
    
    // 计算成功和失败的数量
    const totalCount = results.length;
    const successCount = results.filter(result => result.success).length;
    const failCount = totalCount - successCount;
    
    statsDiv.innerHTML = `总共处理: <strong>${totalCount}</strong> 条订单, 成功: <strong style="color: green">${successCount}</strong>, 失败: <strong style="color: red">${failCount}</strong>`;
    resultContainer.appendChild(statsDiv);
    
    // 创建结果表格
    const resultTable = document.createElement('table');
    resultTable.className = 'result-table';
    resultTable.style.width = '100%';
    resultTable.style.borderCollapse = 'collapse';
    resultTable.style.marginTop = '10px';
    
    // 创建表头
    const thead = document.createElement('thead');
    const headerRow = document.createElement('tr');
    ['订单号', '状态', '详情', '记录状态'].forEach(text => {
        const th = document.createElement('th');
        th.textContent = text;
        th.style.padding = '8px';
        th.style.borderBottom = '2px solid #ddd';
        th.style.textAlign = 'left';
        headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    resultTable.appendChild(thead);
    
    // 创建表格内容
    const tbody = document.createElement('tbody');
    results.forEach(result => {
        const row = document.createElement('tr');
        
        // 订单号
        const orderNoCell = document.createElement('td');
        orderNoCell.textContent = result.orderNo || '-';
        orderNoCell.style.padding = '8px';
        orderNoCell.style.borderBottom = '1px solid #ddd';
        row.appendChild(orderNoCell);
        
        // 状态
        const successCell = document.createElement('td');
        successCell.textContent = result.success ? '成功' : '失败';
        successCell.style.padding = '8px';
        successCell.style.borderBottom = '1px solid #ddd';
        successCell.style.color = result.success ? 'green' : 'red';
        successCell.style.fontWeight = 'bold';
        row.appendChild(successCell);
        
        // 详情
        const messageCell = document.createElement('td');
        messageCell.textContent = result.message || '-';
        messageCell.style.padding = '8px';
        messageCell.style.borderBottom = '1px solid #ddd';
        row.appendChild(messageCell);
        
        // 监控记录状态
        const monitoringCell = document.createElement('td');
        monitoringCell.style.padding = '8px';
        monitoringCell.style.borderBottom = '1px solid #ddd';
        
        // 添加调试日志
        console.log(`订单 ${result.orderNo} 的监控状态:`, {
            hasMonitoringStatus: result.hasOwnProperty('monitoringStatus'),
            monitoringStatus: result.monitoringStatus,
            monitoringStatusType: typeof result.monitoringStatus,
            monitoringStatusStringified: JSON.stringify(result.monitoringStatus),
            monitoringMessage: result.monitoringMessage
        });
        
        // 根据监控状态设置显示内容和样式
        if (result.success) {
            if (result.monitoringStatus === true) {
                monitoringCell.textContent = '记录成功';
                monitoringCell.style.color = 'green';
                monitoringCell.title = result.monitoringMessage || '监控数据发送成功';
            } else if (result.monitoringStatus === false) {
                monitoringCell.textContent = '记录失败';
                monitoringCell.style.color = 'orange';
                monitoringCell.title = result.monitoringMessage || '监控数据发送失败';
            } else {
                monitoringCell.textContent = '未记录';
                monitoringCell.style.color = 'gray';
                monitoringCell.title = '未尝试发送监控数据';
            }
        } else {
            monitoringCell.textContent = '不适用';
            monitoringCell.style.color = 'gray';
            monitoringCell.title = '操作未成功，不发送监控数据';
        }
        
        row.appendChild(monitoringCell);
        
        tbody.appendChild(row);
    });
    resultTable.appendChild(tbody);
    
    resultContainer.appendChild(resultTable);
}

// 在DOM加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 初始化应用
    init();
    
    // 设置默认值
    if (switchElement) switchElement.checked = true; // 默认PRD环境
    if (headlessSwitchElement) headlessSwitchElement.checked = false; // 默认隐藏步骤
});